package thread;

import interface_test.sharp.C;

import java.util.Random;

/** 实现多线程数组求和.
 * @author yuisama
 * @date 2022/06/17 19:14
 **/
class Counter {
    int evenSum;
    int oddSum;
}


public class ThreadHomeWork1 {
    public static void main(String[] args) throws InterruptedException {
        int[] num = new int[1000_0000];
        Random random = new Random();
        Counter counter = new Counter();
        for (int i = 0; i < num.length; i++) {
            num[i] = random.nextInt(100) + 1;
        }
        long start = System.nanoTime();
        // 匿名内部类的内部，无法改变方法中的局部变量
        Thread t1 = new Thread(() -> {
            int evenSum = 0;
            for (int i = 0; i < num.length; i = i + 2) {
                evenSum += num[i];
            }
            counter.evenSum = evenSum;
        },"子线程");
        t1.start();
        // 主线程执行数组奇数的元素和
        for (int i = 1; i < num.length; i += 2) {
            counter.oddSum += num[i];
        }
        // 最终汇总结果，需要保证子线程执行完毕再汇总
        t1.join();
        // 此时代码走到这里，说明t1子线程全部执行完毕
        System.out.println("总和为 : " + (counter.evenSum + counter.oddSum));
        long end = System.nanoTime();
        System.out.println("总耗时为 : " + ((end - start) * 1.0 / 1000 / 1000) + "ms");
    }
}